//
//  WCAppDlegate+baidu.m
//  WC
//
//  Created by wsj2015 on 16/2/24.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCAppDlegate+baidu.h"
//#import "WCMainNewViewController.h"

#import "BPush.h"
#import "WCBaiduPushBindHelp.h"
#import "JCAlertView.h"
#import "WCNNavigationController.h"
#import "WCBPushToolByWsj.h"
#import "cwqMessageTypesVC.h"
@implementation WCNAppDelegate (baidu)
- (void)baiduApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    
    BPushMode pushMode ;
    BOOL isDebug;
#if DEBUG
    pushMode = BPushModeDevelopment;
    isDebug = YES;
#else
    pushMode = BPushModeProduction;
    isDebug = NO;
#endif
    
    // iOS8 下需要使用新的 API
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }

    // 在 App 启动时注册百度云推送服务，需要提供 Apikey
//    [BPush registerChannel:launchOptions apiKey:@"xU1Rk8SqQGkaqSzEbw6TtkuL" pushMode:pushMode withFirstAction:nil withSecondAction:nil withCategory:nil isDebug:isDebug];

    [BPush registerChannel:launchOptions apiKey:@"xU1Rk8SqQGkaqSzEbw6TtkuL" pushMode:pushMode withFirstAction:@"打开" withSecondAction:@"回复" withCategory:nil useBehaviorTextInput:YES isDebug:isDebug];
    [BPush disableLbs];
    [WCBaiduPushBindHelp bindToService];
    if (launchOptions) {
        NSDictionary*userInfo = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
        //从杀死状态启动  且通知来自百度推送
        if (userInfo &&!userInfo[@"m"]) {
            
            NSInteger num =[userInfo[@"aps"][@"badge"] integerValue];
            if (num && num>0) {
                [WCBPushToolByWsj saveNewBadge:num];
            }

            [JCAlertView showTwoButtonsWithTitle:@"后台收到推送通知" Message:userInfo[@"aps"][@"alert"] ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"忽略" Click:^{
                
            } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"前往查看" Click:^{
                
                WCNNavigationController *nav =[[[[UIApplication sharedApplication] delegate] window] rootViewController];
                [nav pushViewController:[cwqMessageTypesVC new] animated:YES];
                
//                WCMainNewViewController *tbc =[[UIApplication sharedApplication].delegate window].rootViewController;
//                tbc.selectedIndex = 3;
//                
//                [tbc.selectedViewController pushViewController:[cwqMessageTypesVC new] animated:YES];
                
            }];

        }
       
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    //    推送来来自百度
    if (userInfo[@"aps"] &&!userInfo[@"m"]) {
        if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
            UIApplicationState state = [[UIApplication sharedApplication] applicationState];
            switch (state) {
                case UIApplicationStateActive:
                    [self playSoundAndVibration];
                    [JCAlertView showTwoButtonsWithTitle:@"通知" Message:userInfo[@"aps"][@"alert"] ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"忽略" Click:^{
                        
                    } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"前往查看" Click:^{
                        WCNNavigationController *nav =[[[[UIApplication sharedApplication] delegate] window] rootViewController];
                        [nav pushViewController:[cwqMessageTypesVC new] animated:YES];
                        
                    }];
                    
                    break;
                case UIApplicationStateInactive:
                    [JCAlertView showTwoButtonsWithTitle:@"通知" Message:userInfo[@"aps"] ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"忽略" Click:^{
                        
                    } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"前往查看" Click:^{
                        WCNNavigationController *nav =[[[[UIApplication sharedApplication] delegate] window] rootViewController];
                        [nav pushViewController:[cwqMessageTypesVC new] animated:YES];
                        
                    }];
                    
                    [self playSoundAndVibration];
                    break;
                case UIApplicationStateBackground:

                    break;
                default:
                    
                    break;
            }
            
            
        }else{
            
        }

    }

}


// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    
    [application registerForRemoteNotifications];
    
    
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"test:%@",deviceToken);
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        // 需要在绑定成功后进行 settag listtag deletetag unbind 操作否则会失败
        
        // 网络错误
        if (error) {
            return ;
        }
        if (result) {
            // 确认绑定成功
            if ([result[@"error_code"]intValue]!=0) {
                return;
            }
            // 获取channel_id
            NSString *myChannel_id = [BPush getChannelId];
            NSLog(@"==%@",myChannel_id);
            
            [BPush listTagsWithCompleteHandler:^(id result, NSError *error) {
                if (result) {
                    NSLog(@"result ============== %@",result);
                }
            }];
            [BPush setTag:@"Mytag" withCompleteHandler:^(id result, NSError *error) {
                if (result) {
                    NSLog(@"设置tag成功");
                }
            }];
        }
    }];
    
}

// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"DeviceToken 获取失败，原因：%@",error);
}


- (void)playSoundAndVibration{
    
    
    // 收到消息时，播放音频
//    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
//    // 收到消息时，震动
//    [[EMCDDeviceManager sharedInstance] playVibration];
}

@end
